<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--元素库管理-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-select v-model="cateNamespace" @change="handleSelectCateGroup" clearable style="width: 100%;">
            <el-option v-for="item in cateGroupCodeOptions" :key="item.dictValue" :label="item.dictLabel"
                       :value="item.dictValue" />
          </el-select>
        </div>
        <div class="head-container" :style="{height:slbHeight}">
          <el-scrollbar style="height:100%;">
            <el-tree :data="categoryTreeData" :expand-on-click-node="false" node-key="value"
                     ref="tree" :filter-node-method="filterTree" highlight-current :props="defaultProps"
                     :default-expand-all="false"
                     @node-click="getCheckedKeys">
              <template #default="{ node }" >
                <span class="custom-tree-node" :title="node.label">
                  <span>
<!--                    <i class="el-icon-folder-opened" v-if="data.iconSkin === 'root-category'"></i>-->
<!--                    <i class="el-icon-s-operation text-warning" v-else-if="data.iconSkin === 'sub-category'"></i>-->
<!--                    <i class="el-icon-folder-closed" v-else></i>-->
                    {{ node.label }}
                  </span>
                </span>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="元素名称" prop="elementNameLike">
                <el-input v-model="queryParams.elementNameLike" placeholder="请输入元素名称" clearable
                          @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="元素编码" prop="elementCodeLike">
                <el-input v-model="queryParams.elementCodeLike" placeholder="请输入元素编码" clearable
                          @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <!--              <el-form-item prop="isTypeCond" label="元素类型" >-->
              <!--                <el-checkbox-group v-model="queryParams.isTypeCond" size="medium">-->
              <!--                  <el-checkbox true-label="Y" false-label="N" checked>{{"条件元素"}}</el-checkbox>-->
              <!--                </el-checkbox-group>-->
              <!--              </el-form-item>-->
              <!--              <el-form-item prop="isTypeAction" label="">-->
              <!--                <el-checkbox-group v-model="queryParams.isTypeAction" size="medium">-->
              <!--                  <el-checkbox true-label="Y" false-label="N" checked>{{"动作元素"}}</el-checkbox>-->
              <!--                </el-checkbox-group>-->
              <!--              </el-form-item>-->

              <el-form-item label="元素类型" prop="elementType">
                <el-radio-group v-model="queryParams.elementType">
                  <el-radio key="all" label="all">全部</el-radio>
                  <el-radio v-for="dict in elementTypeOptions" :key="dict.dictValue" :label="dict.dictValue">
                    {{ dict.dictLabel }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <search-button @click="handleQuery" :perm="['rule:element:search']" />
                <reset-button @click="resetQuery" :perm="['rule:element:search']" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <add-button @click="handleAdd" :perm="['rule:element:insert']" :roleType="['app']"
                      v-if="selectOption && selectOption.params.cateParentId === '0'"/>
          <select-button @click="handleSelect" :perm="['rule:element:search']" :roleType="['app']" text="选择"
                         v-if="selectOption && selectOption.params.cateParentId !== '0'" />
          <right-toolbar :showSearch="showSearch" @queryTable="getList" :perm="['rule:element:search']" />
        </el-row>
        <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="元素名称" prop="elementName" :show-overflow-tooltip="true" width="120" />
          <el-table-column label="元素编码" prop="elementCode" :show-overflow-tooltip="true" min-width="250" />
          <el-table-column label="映射类型" prop="mappingType" align="center" min-width="110">
            <template v-slot="scope">{{ selectDictLabel(mappingTypeOptions, scope.row.mappingType) }}</template>
          </el-table-column>
          <el-table-column label="视图类型" prop="viewType" align="center" min-width="110">
            <template v-slot="scope">{{ selectDictLabel(viewTypeOptions, scope.row.viewType) }}</template>
          </el-table-column>
          <el-table-column label="元素类型" prop="typeCond" align="center" min-width="110">
            <template v-slot="scope">{{
                selectDictLabel(typeOptions, scope.row.isTypeCond === 'Y' ? (scope.row.isTypeAction === 'Y' ? 3 : 1) : (scope.row.isTypeAction === 'Y' ? 2 : 0))
              }}
            </template>
          </el-table-column>
          <el-table-column label="是否有效" prop="isEnable" align="center" width="80">
            <template v-slot="scope">{{ selectDictLabel(isEnableOptions, scope.row.isEnable) }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width"
                           v-if="hasRoleType(['app'])">
            <template v-slot="scope">
              <text-delete-button @click="handleDelete(scope.row)" :perm="['rule:element:delete']"
                                  :roleType="['app']"
                                  v-if="selectOption && selectOption.params.cateParentId === '0'"
                                  :title="'是否确认删除记录'+scope.row.elementId+'?'"/>
              <text-edit-button @click="handleUpdate(scope.row)" :perm="['rule:element:update']"
                                v-if="selectOption && selectOption.params.cateParentId === '0'"
                                :roleType="['app']"/>
              <el-link size="mini" icon="el-icon-copy-document"
                         v-if="selectOption && selectOption.params.cateParentId === '0'"
                         class="copyBtn"
                         @click="copyHandler(scope.row)">复制
              </el-link>

              <text-delete-button @click="handleDeleteRelation(scope.row)" :perm="['rule:element:delete']"
                                  :roleType="['app']" text="移除"
                                  v-if="selectOption && selectOption.params.cateParentId !== '0'"
                                  :title="'是否确认移除记录'+scope.row.elementId+'?'" />
              <text-detail-button @click="handleView(scope.row)" :perm="['rule:element:search']"
                                  v-if="selectOption && selectOption.params.cateParentId !== '0'"
                                  :roleType="['app']" />

              <el-link title="上移" icon="el-icon-arrow-up" :disabled="0 === scope.$index"
                         v-if="selectOption && selectOption.params.cateParentId !== '0'" :class="{'disabled_color':0 === scope.$index}"
                         @click="upRow(scope.row,scope.$index)">上移
              </el-link>
              <el-link title="下移" icon="el-icon-arrow-down"
                         :disabled="scope.$index === dataList.length - 1"
                         :class="{'disabled_color':scope.$index === dataList.length - 1}"
                         v-if="selectOption && selectOption.params.cateParentId !== '0'"
                         @click="downRow(scope.row,scope.$index)">下移
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
                    @pagination="getList" />
        <handle :editForm="editForm" ref="handleRef"
                :cateGroupCodeOptions="cateGroupCodeOptions"
                :isTypeActionOptions="isTypeActionOptions"
                :elementTypeOptions="elementTypeOptions"
                :isEnableOptions="isEnableOptions"
                :viewTypeOptions="viewTypeOptions"
                :mappingTypeOptions="mappingTypeOptions"
                :typeOptions="typeOptions"
                :convertTypeOptions="convertTypeOptions"
                :viewDateSourceTypes="viewDateSourceTypes"
                @getList="getList"
                @reset="reset" />
        <selectElement :selectForm="selectForm" ref="selectElementRef"
                       :mappingTypeOptions="mappingTypeOptions"
                       :isEnableOptions="isEnableOptions"
                       @getList="getList" />
      </el-col>
    </el-row>

  </div>

</template>

<script>
import { reactive } from 'vue';
import {
  search,
  deleteByIds,
  deleteByEntry,
  selectById,
  elementInfoList,
  elementListByParentCategoryCode,
  elementSort
} from "@/platform/uni/api/uni/element/index.ts";
import {deleteByEntry as deleteElementRelation} from "@/platform/uni/api/uni/element/index.ts";
import {categoryTreeList} from "@/platform/uni/api/uni/element/index.ts";
import {debounceWrapper} from "@/utils/zmids.ts";
import handle from './handle.vue';
import selectElement from './select.vue';
import {searchAll as entitySearchAll} from '@/platform/uni/api/uni/element/index.ts'
// import {deepClone} from "@/utils/index.js";

function createEditForm() {
  return {
    // 控制 dialog
    open: false,
    // 弹出层标题
    title: '',
    // 是否修改操作
    isModify: false,
    //实体对象列表
    entityObjectList: [],
    //是否为查看
    disabled: false,
    parentCategoryCode: '',
    // 表单参数
    data: {
      elementType: [],
      elementTypeCopy: '',
      elementName: '',
      elementCode: '',
      isEnable: 'Y',
      paramObjectName: '',
      paramObjectAttr: '',
      mappingType: '',
      viewType: '',
      mappingValue: '',
      convertType: '',
      convertValue: '',
      remark: '',
      isTypeCond: 'Y',
      isTypeAction: 'N',
      isDelete: 'N',
      sort: 0,
      viewDataSourceType: '',
      viewDataSourceValue: '',
      dependentElement: '',
      dependentElementName: '',
      showField: '',
      valueField: ''
    },
    // 规则
    rules: {
      // 元素编码
      elementCode: [
        {required: true, message: '元素编码不可以为空', trigger: 'blur'}
        , {min: 1, max: 64, message: "元素编码的长度最多 64 个字符", trigger: "blur"}
      ],
      // 元素名称
      elementName: [
        {required: true, message: '元素名称不可以为空', trigger: 'blur'}
        , {min: 1, max: 64, message: "元素名称的长度最多 64 个字符", trigger: "blur"}
      ],
      elementTypeCopy: [
        // {required: true, message: '元素类型不可以为空', trigger: 'change'}
      ],
      viewType: [
        {required: true, message: '视图类型不可以为空', trigger: 'change'}
      ],
      // viewDataSourceType: [
      //   {required: true, message: '视图数据源类型不可以为空', trigger: 'change'}
      // ],
      // 规则对象
      paramObjectName: [
        {required: true, message: '规则对象不可以为空', trigger: 'blur'}
        , {min: 1, max: 64, message: "规则对象的长度最多 64 个字符", trigger: "blur"}
      ],
      // 规则对象属性
      paramObjectAttr: [
        {required: true, message: '规则对象属性不可以为空', trigger: 'blur'}
        , {min: 1, max: 64, message: "规则对象属性的长度最多 64 个字符", trigger: "blur"}
      ],
    },
  }
}

export default {
  // 此处的名字需要与菜单中Path一致，否则多Tab页切换时会刷新
  name: 'CompontElement',
  components: {handle, selectElement},
  data() {
    return {
      slbHeight: '',
      clientHeight: '',//可视区域高度
      selectForm: {
        // 控制 dialog
        open: false,
        // 弹出层标题
        title: '',
        // 是否修改操作
        isModify: false,
        // 分类id
        cateId: '',
        parentCategoryCode: ''
      },
      // cateNamespace: 'ZHDD_BUSINESS_RULE_TYPE',
      cateNamespace: '',
      selectOption: undefined,
      //分类管理树
      //elementTreeData: require('../../../rule/data.json').data,// [],
      categoryTreeData: [],
      categoryDataList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      cateGroupCodeOptions: [],
      // 是否条件元素的固定字典选项列表
      elementTypeOptions: [{"dictValue": "cond", "dictLabel": "条件元素"}, {
        "dictValue": "action",
        "dictLabel": "动作元素"
      }],
      // 是否动作元素的固定字典选项列表
      isTypeActionOptions: [{"dictValue": "Y", "dictLabel": "是"}, {"dictValue": "N", "dictLabel": "否"}],
      // 是否有效的固定字典选项列表
      isEnableOptions: [{"dictValue": "Y", "dictLabel": "有效"}, {"dictValue": "N", "dictLabel": "无效"}],
      // 映射类型的数据字典选项列表：uni_mapping_type
      mappingTypeOptions: [],
      // 视图类型的数据字典选项列表：uni_view_type
      viewTypeOptions: [],
      // 视图数据源类型：uni_view_date_source_type
      viewDateSourceTypes: [],
      //转换方式字典
      convertTypeOptions: [],
      // 元素类型固定字典选项列表
      typeOptions: [{"dictValue": 1, "dictLabel": "条件元素"}, {
        "dictValue": 2,
        "dictLabel": "动作元素"
      }, {"dictValue": 3, "dictLabel": "条件、动作元素"}],
      // 是否删除的固定字典选项列表
      isDeleteOptions: [{"dictValue": "Y", "dictLabel": "是"}, {"dictValue": "N", "dictLabel": "否"}],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 元素ID
        elementId: undefined,
        // 元素编码
        elementCodeLike: '',
        // 元素名称
        elementNameLike: '',
        // 是否条件元素
        isTypeCond: '',
        // 是否动作元素
        isTypeAction: '',
        //元素类型
        elementType: 'all',
      },
      editForm: createEditForm(),
    };
  },
  mounted() {
    this.clientHeight = `${document.getElementsByClassName('app-main')[0].clientHeight}`;
    this.slbHeight = this.clientHeight - 60 + 'px';
  },
  created() {
    // 查询列表
    this.getList();
    // 获取数据字典：RULE_CATE_GROUP
    this.getDicts("uni_cate_namespace").then(response => {
      this.cateGroupCodeOptions = response.data;
      this.cateNamespace = response.data[0].dictValue
      console.log(this.cateNamespace)

      //查询分类树
      this.getCategoryTreeList();
    });
    // 获取数据字典：uni_mapping_type
    this.getDicts("uni_mapping_type").then(response => {
      this.mappingTypeOptions = response.data;
    });
    // 获取数据字典：uni_view_type
    this.getDicts("uni_view_type").then(response => {
      this.viewTypeOptions = response.data;
    });
    // 获取数据字典：RULE_CONVERT_TYPE
    this.getDicts("RULE_CONVERSION_MODE").then(response => {
      this.convertTypeOptions = response.data;
    });
    // 获取数据字典：uni_view_date_source_type
    this.getDicts("uni_view_date_source_type").then(response => {
      this.viewDateSourceTypes = response.data;
    });
  },
  // watch: {
  //   // 根据名称筛选分类树
  //   cateNamespace(val) {
  //     this.$refs.tree.filter(val);
  //   }
  // },
  methods: {


    /**
     * 根据所属分组改变列表信息
     */
    handleSelectCateGroup: debounceWrapper(function (val) {
      this.cateNamespace = val;
      this.selectOption = undefined
      this.getCategoryTreeList();
    }),
    //选择分类树节点
    getCheckedKeys(categoryTreeData, node) {
      this.selectOption = this.$options.data().selectOption;
      this.$nextTick(()=>{
        console.log('categoryTreeData',categoryTreeData)
        this.selectOption = categoryTreeData;
        this.selectOption.pValue = node?.parent?.data?.value;
        this.getList();
      })
    },
    getCategoryTreeList: debounceWrapper(function () {
      this.loading = true;
      categoryTreeList({
        cateNamespace: this.cateNamespace
      }).then(response => {
        this.categoryTreeData = response.data;
        console.log('categoryTreeData',this.categoryTreeData)

        this.dataList = [];
        this.total = 0;
        this.loading = false;
      });
    }),
    //过滤树
    filterTree(value, data) {
      if (!value) return true;
      return data.cateNamespace.indexOf(value) !== -1;
    },

    // 查询列表
    getList: debounceWrapper(function () {
      this.loading = true;
      this.queryParams.cateId = this.selectOption?.id;
      elementInfoList(this.queryParams).then(
        response => {
          this.dataList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    }),
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      // this.editForm = this.$options.data().editForm;
      // console.log(createEditForm())
      // this.editForm = createEditForm()
      this.$nextTick(() => {
        this.$refs.handleRef.resetCurrentForm();
        // this.$refs.selectElementRef.resetCurrentForm();
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 所有选中的ID
      this.ids = selection.map(item => item.elementId)
    },

    //获取规则属性
    getEntityObject: debounceWrapper(function (callback) {
      //获取规则对象
      let queryParams = {
        parentId: 0,
        isObject: 'Y',
        cateNamespace: this.cateNamespace
      }
      entitySearchAll(queryParams).then(response => {
        this.editForm.entityObjectList = response.data;
        if (callback) callback();
      });
    }),

    // 新增按钮操作
    handleAdd() {
      //判断是否选择分类
      if (!this.selectOption) {
        this.$message.error("请先选择分类");
        return;
      }
      console.log(this.selectOption)

      // //校验是否是根分类，只有根分类才能新增元素
      // if(this.selectOption.parentCategoryCode !='' && this.selectOption.parentCategoryCode != null){
      //   alert('请选择根目录')
      //   return;
      // }
      this.reset();
      //获取规则对象
      this.getEntityObject(() => {
        this.editForm.data = {
          elementType: [],
          elementTypeCopy: '',
          elementName: '',
          elementCode: '',
          isEnable: 'Y',
          paramObjectName: '',
          paramObjectAttr: '',
          mappingType: '',
          viewType: '',
          mappingValue: '',
          convertType: '',
          convertValue: '',
          remark: '',
          isTypeCond: 'Y',
          isTypeAction: 'N',
          isDelete: 'N',
          sort: 0,
          viewDataSourceType: '',
          viewDataSourceValue: '',
          dependentElement: '',
          dependentElementName: '',
          showField: '',
          valueField: ''
        }
        this.editForm.data.cateId = this.selectOption?.id;
        this.editForm.data.cateName = this.selectOption?.name;
        //非表单入参赋值
        this.editForm.isModify = false;
        this.editForm.title = "新增元素信息表";
        this.editForm.open = true;
        this.$nextTick(() => {
          this.$refs.handleRef.setListItem({
            parentCategoryCode: this.selectOption?.params.cateCode,
            cateId: this.editForm.data.cateId
          })
        })
      });

    },
    // 移除按钮操作
    handleDeleteRelation: debounceWrapper(function (row) {
      let deleteParam = {
        cateId: this.selectOption?.id,
        elementId: row.elementId
      };

      deleteElementRelation(deleteParam)
        .then(() => {
          this.getList();
          this.msgSuccess("移除成功");
        }).catch(function () {
      });
    }),
    // 删除按钮操作
    handleDelete: debounceWrapper(function (row) {
      let deleteParam = {
        cateId: this.selectOption?.id,
        elementId: row.elementId
      };

      deleteByEntry(deleteParam)
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
      });
    }),
    // 修改按钮操作
    handleUpdate: debounceWrapper(function (row) {
      // this.reset();
      selectById(row.elementId).then(response => {
        this.getEntityObject(() => {
          this.editForm.data = response.data || {};
          this.editForm.isModify = true;
          this.editForm.title = "修改元素信息表";
          //获取规则对象
          this.editForm.open = true;
          this.$nextTick(() => {
            this.editForm.data.cateId = this.selectOption?.id;
            this.editForm.data.cateName = this.selectOption?.name;
            this.$refs.handleRef.setListItem({
              // parentCategoryCode: this.selectOption?.id?.substring(5),
              parentCategoryCode: this.selectOption?.params.cateCode,
              cateId: this.selectOption?.id
            })
          })
        });

      });
    }),
    // 查看按钮操作
    handleView: debounceWrapper(function (row) {
      this.reset();
      selectById(row.elementId).then(response => {
        //获取规则对象
        this.getEntityObject(() => {
          this.editForm.data = response.data || {};
          this.editForm.isModify = true;
          this.editForm.title = "查看元素信息表";
          this.editForm.disabled = true;
          this.editForm.data.cateName = this.selectOption?.name;
          this.editForm.open = true;

        });

      });
    }),
    // 选择按钮
    handleSelect() {
      //获取父分类的元素列表
      // this.getParentElementList();

      // this.selectForm.parentCategoryCode = this.selectOption?.pId?.substring(5);
      this.selectForm.parentCategoryCode = this.selectOption?.params.parentCateCode
      this.selectForm.isModify = false;
      this.selectForm.title = "选择元素";
      this.selectForm.cateId = this.selectOption?.id;
      this.selectForm.open = true;
      this.$nextTick(() => {
        this.$refs.selectElementRef.getParentElementList();
      })
    },
    // 复制按钮
    copyHandler(row) {

      //判断是否选择分类
      if (!this.selectOption) {
        this.$message.error("请先选择分类");
        return;
      }
      this.reset();
      selectById(row.elementId).then(response => {
        this.editForm.data = response.data || {};
        //获取规则对象
        this.getEntityObject(() => {
          this.editForm.data.cateId = this.selectOption?.id;
          this.editForm.data.cateName = this.selectOption?.name;
          this.editForm.data.sort = 0;
          this.editForm.isModify = false;
          this.editForm.title = "新增元素信息表";
          this.editForm.cateId = this.selectOption?.id;
          this.editForm.open = true;
        });
      });
    },
    // 上移
    upRow(e, t) {
      this.dataList[t].sort = this.dataList[t].sort - 1;
      this.dataList[t - 1].sort = this.dataList[t - 1].sort + 1;
      this.dataList = this.arrayMove(this.dataList, e, "up")

      let moveParam = {
        moveNum: 1,
        cateId: this.selectOption?.id,
        elementId: this.dataList[t].elementId,
      }
      elementSort(moveParam).then(response => {
      });
    },
    // 下移
    downRow(e, t) {
      this.dataList[t].sort = this.dataList[t].sort + 1;
      this.dataList[t + 1].sort = this.dataList[t + 1].sort - 1;
      this.dataList = this.arrayMove(this.dataList, e, "down")

      let moveParam = {
        moveNum: -1,
        cateId: this.selectOption?.id,
        elementId: this.dataList[t].elementId,
      }
      elementSort(moveParam).then(response => {
      });
    },
    arrayMove: (e, t, n) => {
      if (n = n || "down", !t || t.constructor !== Object && t.constructor !== Array) return e;
      if (t.constructor === Object && (t = [t]), "up" == n) t.forEach(t => {
        let n = e.indexOf(t, 1);
        if (n > 0) {
          let t = [...e];
          t[n - 1] = e[n], t[n] = e[n - 1], e = t
        }
      }); else if ("down" == n) for (var i, o = t.length - 1; i = t[o--];) {
        let t = e.indexOf(i, 0);
        if (t > -1 && t < e.length - 1) {
          let n = [...e];
          n[t + 1] = e[t], n[t] = e[t + 1], e = n
        }
      }
      return e
    },
  },
}
</script>

<style scoped lang="scss">
//.head-container {
//  //margin-bottom: 10px;
//}
.disabled_color{
  color: #C0C4CC !important;
}

.custom-tree-node {
  font-size: 14px;
}
.el-icon-folder-opened,
.el-icon-s-operation,
.el-icon-folder-closed {
  display: inline-block;
}
.copyBtn {
  color: #409eff;
  font-size: 12px;
  margin-left: 10px;
  text-decoration: none;
}
.copyBtn:hover {
  text-decoration: none;
}
</style>
